<template>
	<MessageArea
		title="评论列表"
		:subTitle="`(${datas.total})`"
		:list="datas.rows"
		:isListLoading="isLoading"
		@submited="handleSubmit"
	/>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import { getComments, postComment } from "@/api/getBlog";
import fetchDatas from "@/mixins/fetchDatas";
import eventBus from "@/eventBus";
export default {
	mixins: [fetchDatas({ total: 0, rows: [] })],
	components: {
		MessageArea,
	},
	data() {
		return { page: 1, limit: 10 };
	},
	computed: {
		hasMore() {
			return this.datas.rows.length < this.datas.total;
		},
	},
	methods: {
		async fetchData() {
			return await getComments(
				this.page,
				this.limit,
				this.$route.params.blogId
			);
		},
		//加载更多评论
		async fetchMore() {
			if (!this.hasMore) {
				//已经加载完全部评论
				return;
			}
			//加载下一页
			this.page++;
			this.isLoading = true;
			const resp = await this.fetchData();
			//将获取的数据连接在原始数据的后面
			this.datas.rows = this.datas.rows.concat(resp.rows);
			this.datas.total = resp.total;
			this.isLoading = false;
		},

		handleScroll(dom) {
			if (this.isLoading || !dom) {
				//正在加载中或当前dom不存在
				return;
			}
			const range = 50;
			const gap = Math.abs(dom.scrollTop + dom.clientHeight - dom.scrollHeight);
			if (gap < range) {
				this.fetchMore();
			}
		},
		async handleSubmit(formData, callback) {
			const result = await postComment({
				blogId: this.$route.params.blogId,
				...formData,
			});
			this.datas.rows.unshift(result);
			this.datas.total++;
			callback("评论成功");
		},
	},
	mounted() {
		eventBus.$on("mainScroll", this.handleScroll);
	},
	beforeDestroy() {
		eventBus.$off("mainScroll", this.handleScroll);
	},
};
</script>

<style></style>
